package com.funong.matrix.core.utils.zip;

import com.funong.matrix.core.enums.ResultCodeEnum;
import com.funong.matrix.core.utils.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author NaNa
 * @since 2020-07-09 14:10
 */
public class FileDownloadUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileDownloadUtil.class);

    /**
     * 文件下载
     *
     * @param path     服务器文件相对路径
     * @param response 响应
     * @return 响应下载结果
     */
    public static HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            if (StringUtils.isBlank(path)) {
                throw new BusinessException(ResultCodeEnum.DOWNLOAD_FAILED);
            }
            File file = new File(path);
            if (!file.exists()) {
                throw new BusinessException(ResultCodeEnum.DOWNLOAD_FAILED);
            }
            // 取得文件名。
            String fileName = file.getName();
            fileName = fileName.substring(fileName.indexOf("_") + 1);
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            logger.info("文件下载路径：" + path);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }


}
